package com.ubi.core.framework.job;

import com.ubi.core.framework.settings.ModuleSettings;
import com.ubi.core.framework.spring.SpringObjectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MonitorUnscheduledJob extends MonitoredSchedulerJob implements MonitorJob {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    SpringObjectFactory springObjectFactory;

    @Autowired
    Environment environment;

    @Autowired
    ModuleSettings moduleSettings;

    @Autowired
    Scheduler scheduler;

    @Override
    public void execute() throws Exception {

        logger.info("begin execute MonitorUnscheduledJob.");

        List<MonitoredSchedulerJob> schedulerJobList = springObjectFactory.getBeans(MonitoredSchedulerJob.class);

        List<JobSetting> unScheduledJobSettings = getUnScheduledJob(schedulerJobList);

        if (unScheduledJobSettings.isEmpty())
            return;

        triggerUnScheduledJob(unScheduledJobSettings);

        logger.info("finish execute MonitorUnscheduledJob.");
    }

    void triggerUnScheduledJob(List<JobSetting> unScheduledJobSettings) throws Exception {
        logger.info("begin execute unscheduled job");

        Collections.sort(unScheduledJobSettings, new Comparator<JobSetting>() {
            @Override
            public int compare(JobSetting o1, JobSetting o2) {
                return o1.getLastExecuteTime().before(o2.getLastExecuteTime()) ? -1 : 1;
            }
        });

        //execute the un scheduler job by order
        for (JobSetting unScheduledJobSetting : unScheduledJobSettings) {
            scheduler.triggerRightNow(unScheduledJobSetting.getSchedulerJob());
        }
        logger.info("finish execute unscheduled job");
    }

    private List<JobSetting> getUnScheduledJob(List<MonitoredSchedulerJob> schedulerJobList) {
        logger.info("begin look up unscheduled job ");

        List<JobSetting> unScheduledJobSettings = new ArrayList<>();
        for (SchedulerJob schedulerJob : schedulerJobList) {

            if (MonitorJob.class.isAssignableFrom(schedulerJob.getClass()))
                continue;

            JobSetting jobSetting = JobSetting.getJobSetting(environment, schedulerJob);
            if (!jobSetting.isEnable())
                continue;

            if (jobSetting.getCronExpression() == null)
                continue; //不是定时任务不做check

            unScheduledJobSettings.add(jobSetting);
        }

        logger.info("finish look up unscheduled job,  unscheduled job size:{}", unScheduledJobSettings.size());

        return unScheduledJobSettings;
    }
}
